import numpy as np
import NetFT
import matplotlib.pyplot as plt
import matplotlib.animation as animation
'''
    配置好力传感器才能跑以下程序
'''
netft_ip = "192.168.1.1"
sensor = NetFT.Sensor(netft_ip)
sensor.setbias()

f = open('test.txt', 'w')

def data_gen():
    t = 0
    while True:     # att 1000
        t += 1                                         #横坐标
        yield t, sensor.getNetForce()[2]    #生成x,y坐标

def init():
    ax.set_xlim(0, 100)
    ax.set_ylim(-20, 20)
    del xdata[:]
    del ydata0[:]
    ln[0].set_data(xdata, ydata0)
    return ln,

def update(data):
    t, y0 = data
    f.write(str(t))
    f.write("  ")
    f.write(str(y0))
    f.write("\n")
    xdata.append(t)
    ydata0.append(y0)
    xmin, xmax = ax.get_xlim()          #获取横坐标的最大最小值
    if t >= xmax:                       #当数据横坐标超出图像最大横坐标时
        # ax.set_xlim(xmin, 2*xmax)       #官网样例是横坐标最大值翻倍
        ax.set_xlim(xmin+1, xmax+1)    #我将其改成整体横坐标向右平移一个单位 att the former sentence
        ax.figure.canvas.draw()
    ln[0].set_data(xdata, ydata0)
    return ln



xdata, ydata0 = [], []
fig, ax = plt.subplots()
fig.set_size_inches(5, 5)

ln = plt.plot([], [], 'r-')

ani = animation.FuncAnimation(fig, update, data_gen, interval=10, init_func=init, blit=False)
plt.show()

'''
    画3条的在下面  xyz force
'''


# def data_gen():
#     t = 0
#     while True:     # att 1000
#         t += 1                                         #横坐标
#         yield t, sensor.getNetForce()[0], sensor.getNetForce()[1], sensor.getNetForce()[2]    #生成x,y0,y1,y2坐标
#
#
# def init():
#     ax.set_xlim(0, 100)
#     ax.set_ylim(-20, 20)
#     del xdata[:]
#     del ydata0[:]
#     del ydata1[:]
#     del ydata2[:]
#     ln[0].set_data(xdata, ydata0)
#     ln[1].set_data(xdata, ydata1)
#     ln[2].set_data(xdata, ydata2)
#     return ln,
#
# def update(data):
#     t, y0, y1, y2 = data
#     f.write(str(t))
#     f.write("  ")
#     f.write(str(y0))
#     f.write("  ")
#     f.write(str(y1))
#     f.write("  ")
#     f.write(str(y2))
#     f.write("\n")
#     xdata.append(t)
#     ydata0.append(y0)
#     ydata1.append(y1)
#     ydata2.append(y2)  # update the data
#     xmin, xmax = ax.get_xlim()          #获取横坐标的最大最小值
#     if t >= xmax:                       #当数据横坐标超出图像最大横坐标时
#         # ax.set_xlim(xmin, 2*xmax)       #官网样例是横坐标最大值翻倍
#         ax.set_xlim(xmin+1, xmax+1)    #我将其改成整体横坐标向右平移一个单位 att the former sentence
#         ax.figure.canvas.draw()
#     ln[0].set_data(xdata, ydata0)
#     ln[1].set_data(xdata, ydata1)
#     ln[2].set_data(xdata, ydata2)
#     return ln
#
#
#
# xdata, ydata0, ydata1, ydata2 = [], [], [], []
# fig, ax = plt.subplots()
# fig.set_size_inches(5, 5)
#
# ln = plt.plot([], [], 'r-', [], [], 'b-', [], [], 'g-')
#
# ani = animation.FuncAnimation(fig, update, data_gen, interval=10, init_func=init, blit=False)
# plt.show()
